<script>
import LoginManager from '@/utils/login.js'

// 创建全局登录状态
export const globalLoginState = {
  isLoggedIn: false,
  userInfo: null,
  listeners: [],
  
  // 添加监听器
  addListener(callback) {
    this.listeners.push(callback);
  },
  
  // 移除监听器
  removeListener(callback) {
    const index = this.listeners.indexOf(callback);
    if (index > -1) {
      this.listeners.splice(index, 1);
    }
  },
  
  // 通知所有监听器
  notifyListeners() {
    this.listeners.forEach(callback => callback(this.isLoggedIn, this.userInfo));
  },
  
  // 更新登录状态
  setLoginState(isLoggedIn, userInfo = null) {
    this.isLoggedIn = isLoggedIn;
    this.userInfo = userInfo;
    // 存储openid
    if (userInfo && userInfo.openid) {
      uni.setStorageSync('openid', userInfo.openid);
    }
    this.notifyListeners();
  }
};

export default {
  onLaunch: async function() {
    // 设置启动页显示标记
    uni.setStorageSync('showSplashScreen', true);
    
    // 检查是否禁用自动登录
    const disableAutoLogin = uni.getStorageSync('disableAutoLogin');
    if (disableAutoLogin) {
      console.log('用户已禁用自动登录，跳过静默登录');
      // 清除禁用自动登录标记，下次启动时恢复正常登录流程
      uni.removeStorageSync('disableAutoLogin');
      globalLoginState.setLoginState(false);
    } else {
      try {
        const loginResult = await LoginManager.checkLoginState();
        
        // 更新全局登录状态
        if (loginResult && loginResult.token) {
          globalLoginState.setLoginState(true, loginResult);
        } else {
          globalLoginState.setLoginState(false);
        }
      } catch (e) {
        console.error('登录失败：', e);
        globalLoginState.setLoginState(false);
      }
    }
    
    console.log('App Launch');
    // 获取系统状态栏高度
    const systemInfo = uni.getSystemInfoSync();
    const statusBarHeight = systemInfo.statusBarHeight || 44;
    // 将状态栏高度存储到全局数据中
    getApp().globalData = getApp().globalData || {};
    getApp().globalData.statusBarHeight = statusBarHeight;
    console.log('状态栏高度:', statusBarHeight);
  }
}
</script>

<style>
@import './common/common.css';
	/*每个页面公共css */
</style>
